import torch
from torch import nn
from d2l import torch as d2l
from torch.nn import functional as F


# NiN模型
# def nin_block(in_channels,out_channels,kernel_size,strides,padding):
#     return nn.Sequentia(
#         nn.Conv2d(in_channels,out_channels,kernel_size,strides,padding),
#         nn.ReLU(),nn.Conv2d(out_channels,out_channels,kernel_size=1),
#         nn.ReLU(),nn.Conv2d(out_channels,out_channels,kernel_size=1),
#         nn.ReLU())
# net = nn.Sequential(
#     nin_block(1,96,kernel_size=11,strides=4,padding=0),
#     nn.MaxPool2d(3,stride=2),
#     nin_block(96,256,kernel_size=5,strides=1,padding=2),
#     nn.MaxPool2d(3,stride=2),
#     nin_block(256,384,kernel_size=3,strides=1,padding=1),
#     nn.MaxPool2d(3,stride=2),nn.Dropout(p=0.5),
#     nin_block(384,10,kernel_size=3,strides=1,padding=1),
#     nn.AdaptiveAvgPool2d((1,1)),
#     nn.Flatten())
#
# # GoogLeNet
# class Inception(nn.Module):
#     def __init__(self,in_channels,c1,c2,c3,c4,**kwargs):
#         super(Inception,self).__init__(**kwargs)
#         self.p1_1 = nn.Conv2d(in_channels,c1,kernel_size=1)
#         self.p2_1 = nn.Conv2d(in_channels,c2[0],kernel_size=1)
#         self.p3_1 = nn.Conv2d(in_channels,c3[0],kernel_size=1)
#         self.p3_2 = nn.Conv2d(c3[0],c3[1],kernel_size=5,padding=3)
#         self.p4_1 = nn.MaxPool2d(kernel_size=3,stride=1,padding=3)
#         self.p4_2 = nn.Conv2d(in_channels,c4,kernel_size=1)
#
#     def forward(self,x):
#         p1 = F.relu(self.p1_1(x))
#         p2 = F.relu(self.p2_2(F.relu(self.p2_1(x))))
#         p3 = F.relu(self.p3_2(F.relu(self.p3_1(x))))
#         p4 = F.relu(self.p4_2(self.p4_1(x)))
#         return torch.cat((p1,p2,p3,p4),dim=1)

# 批量归一化
def batch_norm(X,gamma,beta,moving_mean,moving_var,eps,momentum):
    if not torch.is_grad_enabled(): # 非训练
        X_hat = (X - moving_mean)/torch.sqrt_(moving_var+eps)
    else:
        assert len(X.shape) in (2,4)
        if len(X.shape) == 2:
            mean = X.mean(dim=0)
            var = ((X.mean)**2).mean(dim=0)
        else:
            mean = X.mean(dim=(0,2,3),keepdim=True)
            var = ((X - mean)**2).mean(dim=(0,2,3),keepdim=True)
        X_hat = (X -mean)/torch.sqrt_(var + eps)
        moving_mean = momentum*moving_mean+(1.0-momentum)*mean
        moving_var = momentum*moving_var+(1.0-momentum)*var
    Y = gamma * X_hat + beta
    return Y,moving_mean.data,moving_var.data

class BatchNorm(nn.Module):
    def __init__(self,num_features,num_dims):
        super().__init__()
        if num_dims == 2:
            shape = (1,num_features)
        elif num_features == 4:
            shape = (1,num_features,1,1)
        self.gamma = nn.Parameter(torch.ones(shape))
        self.beta = nn.Parameter(torch.zeros(shape))
        self.moving_mean = torch.zeros(shape)
        self.moving_var = torch.ones(shape)

    def forward(self,X):
        if self.moving_mean.device != X.device:
            self.moving_mean = self.moving_mean.to(X.device)
            self.moving_var = self.moving_var.to(X.device) # 移动到gpu上
        Y,self.moving_mean,self.moving_var = batch_norm(
            X,self.gamma,self.beta,self.moving_mean,self.moving_var,eps=1e-5,momentum=0.9)
        return Y


BatchNorm(num_features=2,num_dims=4)

# 掉包
nn.BatchNorm2d(num_features=4)